`

We can even run a for loop on the output of commands such as ls. In

Listing 2-15, we print the names of all files in the current working directory:

#!/bin/bash

for file in $(ls .); do

echo "File: ${file}"

done

Listing 2-15

A for loop to iterate through a list of files in the current directory

We use a for loop to iterate over the output of the ls . command, which

lists the files in the current directory. Each file will be assigned to the file

variable as part of the for loop, so we can then use echo to print its name. This

technique would be useful if we wanted to, for example, perform a file upload of

all files in the directory or even rename them in bulk.

The break and continue statements

Loops can run forever or until a condition is met. But you can also exit a loop

at any point using the break keyword. This keyword provides an alternative to

the exit command, which would cause the entire script, and not just the loop, to

exit. Using break, we can leave the loop and advance to the next code block:

#!/bin/bash

while true; do

echo "in the loop"

break

done

echo "This code block will be reached"

In this case, the last echo command will be executed.

The continue statement is used to jump to the next iteration of a loop. You

can use it to skip a certain value in a sequence. To illustrate this, let’s create three

empty files so we can iterate through them:

$ touch example_file1 example_file2 example_file3

Next, our for loop will write some content to each file, excluding the first

one, example_file1, which it will leave empty (Listing 2-16).

#!/bin/bash

1 for file in example_file*; do

if [[ "${file}" == "example_file1" ]]; then

echo "Skipping the first file."

2 continue

fi

echo "${RANDOM}" > "${file}"

done

Black Hat Bash (Early Access) © 2023 by Dolev Farhi and Nick Aleks